import mysql.connector
from docx import Document

def extract_questions(file_path, question_type):
    document = Document(file_path)
    questions = []
    current_question = None

    for para in document.paragraphs:
        text = para.text.strip()

        if question_type == 'questionsxuanze':  # 选择题
            if text.startswith("Q:"):
                if current_question:
                    questions.append(current_question)
                current_question = {
                    'text': text[2:].strip(),
                    'options': {'A': None, 'B': None, 'C': None, 'D': None},
                    'correct_answer': None
                }
            elif text.startswith("A:") or text.startswith("B:") or text.startswith("C:") or text.startswith("D:"):
                if current_question:
                    current_question['options'][text[0]] = text[2:].strip()
            elif text.startswith("Answer:"):
                if current_question:
                    current_question['correct_answer'] = text[7:].strip()
            if current_question and len(current_question['options']) == 4:
                questions.append(current_question)

        elif question_type == 'question2':  # 判断题
            if text.startswith("Q:"):
                if current_question:
                    questions.append(current_question)
                current_question = {
                    'text': text[2:].strip(),
                    'correct_answer': None
                }
            elif text.startswith("答案:"):
                if current_question:
                    answer_text = text[3:].strip()
                    if answer_text in ['对', '错']:
                        current_question['correct_answer'] = answer_text

        elif question_type == 'questions':  # 主观题
            if text and (text[0].isdigit() and text[1] == '.'):
                if current_question:
                    questions.append(current_question)
                current_question = {'text': text, 'answers': []}
            elif text:
                if current_question:
                    current_question['answers'].append(text)

    if current_question:
        questions.append(current_question)

    return questions

def insert_questions(exam_name, questions, question_type):
    conn = mysql.connector.connect(
        host="localhost",
        user="root",
        password="your_password",  # 替换为实际的数据库密码
        database="school",
        charset='utf8mb4'  # 确保使用 utf8mb4 字符集
    )
    cursor = conn.cursor()

    try:
        sql = "INSERT INTO exams (name) VALUES (%s)"
        cursor.execute(sql, (exam_name,))
        exam_id = cursor.lastrowid

        for question in questions:
            if question_type == 'questionsxuanze':
                sql = """
                INSERT INTO questionsxuanze (exam_id, question_text, a, b, c, d, correct_answer)
                VALUES (%s, %s, %s, %s, %s, %s, %s)
                """
                values = (
                    exam_id, question['text'],
                    question['options']['A'], question['options']['B'],
                    question['options']['C'], question['options']['D'],
                    question['correct_answer']
                )
            elif question_type == 'question2':
                sql = """
                INSERT INTO question2 (exam_id, question_text, correct_answer)
                VALUES (%s, %s, %s)
                """
                values = (exam_id, question['text'], question['correct_answer'])
            elif question_type == 'questions':
                for answer in question['answers']:
                    sql = """
                    INSERT INTO questions_and_answers (exam_name, question_text, answer_text)
                    VALUES (%s, %s, %s)
                    """
                    values = (exam_name, question['text'], answer)
                    cursor.execute(sql, values)

        conn.commit()
    except mysql.connector.Error as err:
        print(f"Error: {err}")
        conn.rollback()
    finally:
        cursor.close()
        conn.close()
